package oa.hleast.xswl.service.activity.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.constant.ConfigKeyConstant;
import oa.hleast.common.utils.DateUtils;
import oa.hleast.common.web.exception.BizException;
import oa.hleast.xswl.common.constant.CommonConstant;
import oa.hleast.xswl.common.enums.ActivityStatusEnum;
import oa.hleast.xswl.common.enums.ActivityType2CreditOperatingEnum;
import oa.hleast.xswl.common.enums.CreditOperatingAndRuleEnum;
import oa.hleast.xswl.mapper.activity.*;
import oa.hleast.xswl.pojo.domain.activity.*;
import oa.hleast.xswl.pojo.dto.UmsUserDto;
import oa.hleast.xswl.pojo.form.activity.ActivityAttrValueDTO;
import oa.hleast.xswl.pojo.form.activity.CmsCommonActivityForm;
import oa.hleast.xswl.pojo.form.activity.ManagerUserForm;
import oa.hleast.xswl.pojo.form.activity.SignInByManagerForm;
import oa.hleast.xswl.pojo.vo.activity.*;
import oa.hleast.xswl.service.ISysCommonConfigService;
import oa.hleast.xswl.service.activity.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
@AllArgsConstructor
public class CmsCommonActivityServiceImpl extends ServiceImpl<CmsCommonActivityMapper, CmsCommonActivity> implements ICmsCommonActivityService {

    private final ICmsActivityAttrValueService attrValueService;
    private final ICmsUserSignUpService signUpService;
    private final CmsUserSignUpMapper signUpMapper;
    private final CmsUserSignInMapper signInMapper;
    private final CmsActivityCalendarMapper calendarMapper;
    private final CmsActivityTemplateMapper templateMapper;
    private final ICmsActivityManagerUserService managerUserService;
    private final ICmsActivityTypeService typeService;
    private final ISysCommonConfigService commonConfigService;
    private final ICmsUserSignInService userSignInService;

    @Override
    public boolean userSignIn(Long userId, Long activityId, Long calenderId, Integer userType) {
        log.info("userId = {} ,activityId = {} ,calenderId = {}", userId, activityId, calenderId);
        CmsCommonActivity activity = this.getById(activityId);

        // 判断是否是特殊的场馆预约
        if (isVenue(activity)) {
            return userSignInForVenue(userId, activityId);
        }

        CmsActivityCalendar calendar = calendarMapper.selectById(calenderId);
        if (ObjectUtils.isEmpty(calendar)) {
            throw new BizException("该活动不存在");
        }

        // 校验是否已签到
        if (isUserSignIn(userId, activityId, calenderId)) {
            throw new BizException("您已经签到过来，请勿重复签到");
        }

        //判断是否在可报名期间 这里先不判断是否在签到时间内
        long signInStartDate = calendar.getActivityStartDate().getTime();
        long signInEndDate = calendar.getActivityEndDate().getTime();
        long nowDate = System.currentTimeMillis();
        if (nowDate < signInStartDate - CommonConstant.MINUTE_LONG_30) {
            throw new BizException("签到时间为课程开始前30分钟，请稍后重试");
        }

        /** 这里注掉,不进行限制
         if (nowDate > signInEndDate) {
         throw new BizException("签到时间已过，请联系管理老师");
         }
         */

        CmsUserSignIn userSignIn = CmsUserSignIn.builder()
                .userId(userId)
                .scenesId(activityId)
                .calendarId(calenderId)
                .signInDate(new Date())
                .userType(userType)
                .type(0)

                .build();
        log.info("userSignIn = {}", userSignIn);


        // TODO 用户签到
        return userSignInService.save(userSignIn);
    }

    @Override
    public Boolean signInFormTeacher(Long managerUserId, List<SignInByManagerForm> formList) {

        log.info("managerUserId = {},  formList = {}", managerUserId, formList);
        List<CmsUserSignIn> pojoList = new ArrayList<>();

        for (SignInByManagerForm form : formList) {
            Long activityId = form.getActivityId();
            Long calenderId = form.getCalenderId();
            Long studentId = form.getStudentId();
            // 校验是否已签到
            if (isUserSignIn(studentId, activityId, calenderId)) {
                log.info("该活动的该场次已经签到过了，activityId = {},calenderId = {},studentId = {}", activityId, calenderId, studentId);
                continue;
            }

            pojoList.add(CmsUserSignIn.builder()
                    .userId(studentId)
                    .scenesId(activityId)
                    .calendarId(calenderId)
                    .signInDate(new Date())
                    .managerUserId(managerUserId)
                    .type(1)
                    .build());

            CmsActivityType activityType = typeService.getById(this.getById(activityId).getActivityTypeId());
            //todo martin
//            appMemberFeignService.increasePointLog(studentId, ActivityType2CreditOperatingEnum.getEnumByCode(activityType.getCode()), "");
        }


        return userSignInService.saveBatch(pojoList);
    }

    /**
     * 管理员管理的活动列表
     */
    @Override
    public List<ShowCommonActivityVo> findAllManagerActivity(Long managerUserId) {
        List<CmsCommonActivity> list = this.baseMapper.findAllManagerActivity(managerUserId);
        log.info("list = {}", list);
        List<ShowCommonActivityVo> voList = conversionToShowActivityVoList(list);
        log.info("voList = {}", voList);
        return voList;
    }

    /**
     * 管理端扫码接口
     */
    @Override
    public List<ManagerCommonActivityVo> managerScanCode(Long managerUserId, Long studentUserId) {

        // 获取管理员当前时间可以验签的 所有课时/场次/日历
        // 签到时间为活动开始前30分钟
        long afterLongDate = System.currentTimeMillis() + CommonConstant.MINUTE_LONG_30;
        List<CmsActivityCalendar> calenderIdList = calendarMapper.findCalenderByManagerUserAndNowDate(managerUserId, new Date(afterLongDate), new Date());
        log.info("calenderIdList ={}", calenderIdList);

        List<ManagerCommonActivityVo> activityIdList = new ArrayList<>();
        for (CmsActivityCalendar calender : calenderIdList) {
            // 该学生是否报名
            boolean isSignUp = signUpService.isSignUpByCalendar(calender.getId(), studentUserId);
            // 该学生是否已签到过
            boolean isSignIn = userSignInService.isSignInByCalendarAndUserId(studentUserId, calender.getId());

            log.info("是否报名 activityId = {},calenderId = {},isSignUp = {}，是否已签到 isSignIn = {}", calender.getActivityId(), calender.getId(), isSignUp, isSignIn);

            if (isSignUp && !isSignIn) {
                CmsCommonActivity activity = this.getById(calender.getActivityId());
                ManagerCommonActivityVo vo = conversionToManagerActivityVo(this.getById(activity.getId()));
                vo.setStudentUserId(studentUserId);
                vo.setCalenderId(calender.getId());
                vo.setActivityStartDate(calender.getActivityStartDate());
                vo.setActivityEndDate(calender.getActivityEndDate());
                activityIdList.add(vo);
            }
        }

        return activityIdList;
    }

    @Override
    public Boolean deleteById(Long id) {

        List<CmsUserSignUp> userSignUpList = signUpMapper.selectList(new LambdaQueryWrapper<CmsUserSignUp>()
                .eq(CmsUserSignUp::getScenesId, id)
        );
        if (userSignUpList.size() > 0) {
            throw new BizException("该活动已经有人报名，您不能删除");
        }
        return this.removeById(id);
    }

    @Override
    public Page<ShowCommonActivityVo> findShowActivity(Integer page, Integer limit, Long activityTypeId) {
        Page<CmsCommonActivity> activityPage = pageList(page, limit, activityTypeId, null);
        if (activityPage.getTotal() == 0) {
            return new Page<>(page, limit);
        }

        Page<ShowCommonActivityVo> voPage = new Page<>(page, limit, activityPage.getTotal());
        List<ShowCommonActivityVo> voList = conversionToShowActivityVoList(activityPage.getRecords());

        voPage.setRecords(voList);

        return voPage;
    }

    @Override
    public CmsActivityTemplate signInAndGetTemplate(Long activityId) {
        // 检查活动是否存在

        // 获取活动状态
        Map<String, Object> activityStatus = getActivityStatus(activityId);
        ActivityStatusEnum statusEnum = (ActivityStatusEnum) activityStatus.get("activityStatus");
        switch (statusEnum) {
            case FINISH:
                throw new BizException("活动已结束");
            case NOT_START:
                throw new BizException("活动未开始");
            default:
                log.info("statusEnum = {}", statusEnum);
        }

        LambdaQueryWrapper<CmsActivityTemplate> queryWrapper = new LambdaQueryWrapper<CmsActivityTemplate>()
                .eq(CmsActivityTemplate::getScenesId, activityId)
                .last("limit 1");
        List<CmsActivityTemplate> list = templateMapper.selectList(queryWrapper);
        if (list.size() != 1) {
            throw new BizException("报名表异常，请联系管理员！");
        }
        return list.get(0);
    }

    /**
     * 获取活动的状态
     */
    @Override
    public Map<String, Object> getActivityStatus(Long activityId) {
        Map<String, Object> map = new HashMap<>();

        LambdaQueryWrapper<CmsActivityCalendar> starDateQueryWrapper = new LambdaQueryWrapper<CmsActivityCalendar>()
                .eq(CmsActivityCalendar::getActivityId, activityId)
                .orderByAsc(CmsActivityCalendar::getActivityStartDate)
                .orderByDesc(CmsActivityCalendar::getGmtCreate)
                .orderByDesc(CmsActivityCalendar::getGmtModified)
                .last("limit 1");

        List<CmsActivityCalendar> startList = calendarMapper.selectList(starDateQueryWrapper);

        LambdaQueryWrapper<CmsActivityCalendar> endDateQueryWrapper = new LambdaQueryWrapper<CmsActivityCalendar>()
                .eq(CmsActivityCalendar::getActivityId, activityId)
                .orderByDesc(CmsActivityCalendar::getActivityEndDate)
                .orderByDesc(CmsActivityCalendar::getGmtCreate)
                .orderByDesc(CmsActivityCalendar::getGmtModified)
                .last("limit 1");

        List<CmsActivityCalendar> endList = calendarMapper.selectList(endDateQueryWrapper);

        if (CollectionUtils.isEmpty(startList) || CollectionUtils.isEmpty(endList)) {
            map.put("activityStatus", ActivityStatusEnum.NOT_START);
            return map;
        }

        // 活动最早的开始时间
        Date startDate = startList.get(0).getActivityStartDate();
        Date endDate = endList.get(0).getActivityEndDate();
        long activityStartDate = startDate.getTime();
        // 活动结束最晚的结束时间
        long activityEndDate = endDate.getTime();

        map.put("activityStartDate", startDate);
        map.put("activityEndDate", endDate);
        map.put("startDateFormat", DateUtils.format(startDate, "yyyy-MM-dd"));
        map.put("endDateFormat", DateUtils.format(endDate, "yyyy-MM-dd"));

        CmsCommonActivity commonActivity = this.getById(activityId);
        // 报名人数满时活动状态未结束
        if (commonActivity.getSignInNum() >= commonActivity.getMaxSignUpNumber()) {
            map.put("activityStatus", ActivityStatusEnum.FINISH);
            return map;
        }

        //当前时间
        long newTime = System.currentTimeMillis();

        if (newTime < activityStartDate) {
            map.put("activityStatus", ActivityStatusEnum.SIGNING_UP);
            return map;
        }
        if (newTime > activityEndDate) {
            map.put("activityStatus", ActivityStatusEnum.FINISH);
            return map;
        }
        if (newTime > activityStartDate && newTime < activityEndDate) {
            map.put("activityStatus", ActivityStatusEnum.RUN);
            return map;
        }

        map.put("activityStatus", ActivityStatusEnum.NOT_START);
        return map;
    }

    @Override
    public List<ManagerCommonActivityVo> getVenueActivity(Long studentUserId, Long managerUserId) {

        // 管理员管理的属于特殊场馆预约的活动
        List<Long> venueActivityTypeIdList = findVenueActivityTypeId();
        if (CollectionUtils.isEmpty(venueActivityTypeIdList)) {
            return new ArrayList<>();
        }

        List<CmsCommonActivity> commonActivityList = new ArrayList<>();
        for (Long activityTypeId : venueActivityTypeIdList) {
            commonActivityList.addAll(this.baseMapper.findByManagerUserAndVenue(managerUserId, activityTypeId));
        }
        log.info("calenderIdList ={}", commonActivityList);

        List<ManagerCommonActivityVo> activityIdList = new ArrayList<>();
        for (CmsCommonActivity commonActivity : commonActivityList) {
            // 该学生是否报名
            boolean isSignUp = signUpService.isSignUpByActivityId(commonActivity.getId(), studentUserId);
            if (!isSignUp) {
                continue;
            }
            // 该学生是否已签到过
            log.info("该学生是否已签到过 activityId = {},studentId = {}", commonActivity.getId(), studentUserId);
            boolean isSignIn = isUserActivitySignIn(studentUserId, commonActivity.getId());
            log.info("isSignIn = {}", isSignIn);
            if (isSignIn) {
                continue;
            }

            ManagerCommonActivityVo vo = conversionToManagerActivityVo(commonActivity);
            vo.setStudentUserId(studentUserId);
            vo.setCalenderId(0L);
            activityIdList.add(vo);
        }
        return activityIdList;
    }

    @Override
    public List<TodayCommonActivityVo> findTodaySignInForTeacher(Long teacherUserId) {
        Long activityTypeId = typeService.getByCode("A_0005").getId();
        // 查找今天属于该老师管理的培训类活动
        List<CmsActivityCalendar> calendarList = this.baseMapper.findTodayManagerActivityCalendar(teacherUserId, activityTypeId);
        List<TodayCommonActivityVo> voList = new ArrayList<>();

        if (CollectionUtils.isEmpty(calendarList) || ObjectUtils.isEmpty(calendarList.get(0))) {
            return voList;
        }

        log.info("calendarList = {}", calendarList);

        for (CmsActivityCalendar calendar : calendarList) {
            TodayCommonActivityVo vo = conversionToTodayVo(this.getById(calendar.getActivityId()));
            vo.setCalenderId(calendar.getId());
            // 是否已签到
            // todo martin
//            vo.setSignIn(userSignInService.isSignInByCalendarAndUserId(teacherUserId, calendar.getId()));
            // 添加 可签到的开始时间与结束时间
            vo.setSignInStartDate(signUpService.getSignInStartDate(calendar));
            vo.setSignInEndDate(signUpService.getSIgnInEndDate(calendar));
            voList.add(vo);
        }

        return voList;
    }

    @Override
    public HttpShowActivitySignUpVo getActivitySignUp(Long id) {
        CmsCommonActivity commonActivity = this.getById(id);
        HttpShowActivitySignUpVo vo = new HttpShowActivitySignUpVo();
        BeanUtil.copyProperties(commonActivity, vo);

        List<CmsUserSignUp> list = signUpService.list(new LambdaQueryWrapper<CmsUserSignUp>()
                .eq(CmsUserSignUp::getScenesId, id)
                .orderByAsc(CmsUserSignUp::getGmtCreate)
                .orderByAsc(CmsUserSignUp::getId)
        );
        List<HttpShowUserSignUpVo> httpSignUp = list.stream().map(signUp -> {
            HttpShowUserSignUpVo httpShowUserSignUpVo = new HttpShowUserSignUpVo();
            BeanUtil.copyProperties(signUp, httpShowUserSignUpVo);
            UmsUserDto umsUserDto = null;
            // todo
//            appMemberFeignService.getUserDtoById(signUp.getUserId()).getData();
            httpShowUserSignUpVo.setUsername(umsUserDto.getFullname());
            httpShowUserSignUpVo.setSignUpDate(DateUtils.format(signUp.getGmtCreate(), "MM月dd日hh时mm分"));
            return httpShowUserSignUpVo;
        }).collect(Collectors.toList());

//        vo.setSignUpVoList(httpSignUp);

        return vo;
    }


    @Override
    public boolean add(CmsCommonActivityForm form) {

        // 1，保存活动
        CmsCommonActivity commonActivity = conversionToPojo(form);
        boolean save = this.save(commonActivity);

        // 2， 保存附属属性
        List<ActivityAttrValueDTO> attrFormList = form.getAttrForm();
        log.info("attrFormList = {}", attrFormList);
        boolean attrSave = true;
        if (CollectionUtils.isNotEmpty(attrFormList) && save) {
            log.info("保存附属属性，attrFormList ={}", attrFormList);
            List<CmsActivityAttrValue> list = attrFormList.stream().map(attrForm -> {
                CmsActivityAttrValue attributes = new CmsActivityAttrValue();
                BeanUtil.copyProperties(attrForm, attributes);
                attributes.setActivityId(commonActivity.getId());
                return attributes;
            }).collect(Collectors.toList());
            attrSave = attrValueService.saveBatch(list);
            log.info("保存附属属性，list => {}", list);
        }

        return save && attrSave;
    }

    @Override
    public boolean update(CmsCommonActivityForm form) {

        CmsCommonActivity pojo = conversionToPojo(form);

        return this.updateById(pojo);
    }

    @Override
    public Page<CmsCommonActivity> pageList(Integer page, Integer limit, Long activityTypeId, Integer display) {
        return this.page(new Page<>(page, limit), new LambdaQueryWrapper<CmsCommonActivity>()
                .eq(CmsCommonActivity::getActivityTypeId, activityTypeId)
                .orderByDesc(CmsCommonActivity::getGmtCreate)
                .orderByDesc(CmsCommonActivity::getGmtModified)
        );
    }

    @Override
    public boolean deleteByIds(List<String> asList) {
        return this.removeByIds(asList);
    }

    @Override
    public ShowCommonActivityVo detail(Long id, Long userId) {
        CmsCommonActivity commonActivity = this.getById(id);
        if (ObjectUtils.isEmpty(commonActivity)) {
            return new ShowCommonActivityVo();
        }
        ShowCommonActivityVo vo = conversionToShowActivityVo(commonActivity);

        // 获取附加属性
        List<ActivityAttrValueDTO> attrList = getAttrList(commonActivity.getId());
        vo.setValueDTOList(attrList);

        Map<String, Object> map = getActivityStatus(id);
        vo.setActivityStatus(((ActivityStatusEnum) map.get("activityStatus")).getCode());
        vo.setSignUpDate(map.get("startDateFormat") + " 至 " + map.get("endDateFormat"));

        // 是否已报名
        if (ObjectUtils.isNotEmpty(userId)) {
            vo.setSignUp(signUpService.isSignUpByActivityId(id, userId));
        }

        log.info("vo = {}", vo);

        return vo;
    }

    @Override
    public Page<CmsCommonActivity> activityPageList(Integer page, Integer limit, Long typeId, boolean dispaly) {
        Page<CmsCommonActivity> list = this.page(new Page<>(page, limit), new LambdaQueryWrapper<CmsCommonActivity>()
                .eq(CmsCommonActivity::getActivityTypeId, typeId)
        );
        return list;
    }

    @Override
    public List<CmsActivityCalendar> findActivityByTime(Long activityId, Integer year, Integer month) {
        CmsCommonActivity commonActivity = this.getById(activityId);
        if (ObjectUtils.isEmpty(commonActivity)) {
            throw new BizException("活动不合法");
        }

        LambdaQueryWrapper<CmsActivityCalendar> queryWrapper = new LambdaQueryWrapper<CmsActivityCalendar>()
                .eq(CmsActivityCalendar::getActivityId, activityId)
                .eq(CmsActivityCalendar::getYear, year)
                .eq(CmsActivityCalendar::getMonth, month)
                .orderByAsc(CmsActivityCalendar::getDay)
                .orderByDesc(CmsActivityCalendar::getGmtCreate)
                .orderByDesc(CmsActivityCalendar::getGmtModified);

        List<CmsActivityCalendar> list = calendarMapper.selectList(queryWrapper);

        log.info("list = {}", list);

        return list;


    }

    @Override
    public List<ShowActivityCalendarVo> pageActivityAfterToday(Integer page, Integer limit, Long activityId) {
        DateTime beginToday = DateUtils.beginOfDay(new Date());
        log.info("beginToDay = {}", beginToday);
        LambdaQueryWrapper<CmsActivityCalendar> queryWrapper = new LambdaQueryWrapper<CmsActivityCalendar>()
                .eq(CmsActivityCalendar::getActivityId, activityId)
                .gt(CmsActivityCalendar::getActivityEndDate, beginToday);

        Page<CmsActivityCalendar> calendarPage = calendarMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<CmsActivityCalendar> records = calendarPage.getRecords();
        List<ShowActivityCalendarVo> voList = records.stream().map(this::conversionToShowCalendarVo).collect(Collectors.toList());

        log.info("voList = {}", voList);
        return voList;
    }


    private ShowActivityCalendarVo conversionToShowCalendarVo(CmsActivityCalendar pojo) {
        ShowActivityCalendarVo vo = new ShowActivityCalendarVo();
        BeanUtil.copyProperties(pojo, vo);

        String activityStartFormat = DateUtil.format(pojo.getActivityStartDate(), "yyyy/MM/dd HH:mm");
        String activityEndFormat = DateUtil.format(pojo.getActivityEndDate(), "HH:mm");
        vo.setDate(activityStartFormat + "~" + activityEndFormat);
        return vo;
    }

    private CmsCommonActivity conversionToPojo(CmsCommonActivityForm form) {
        CmsCommonActivity pojo = new CmsCommonActivity();
        BeanUtil.copyProperties(form, pojo);
        return pojo;
    }

    /**
     * 获取附加属性
     */
    private List<ActivityAttrValueDTO> getAttrList(Long activityId) {
        LambdaQueryWrapper<CmsActivityAttrValue> queryWrapper = new LambdaQueryWrapper<CmsActivityAttrValue>()
                .eq(CmsActivityAttrValue::getActivityId, activityId);
        List<CmsActivityAttrValue> attrValueList = attrValueService.list(queryWrapper);
        List<ActivityAttrValueDTO> attrList = attrValueList.stream().map(this::conversionToAttr).collect(Collectors.toList());
        return attrList;
    }

    private ActivityAttrValueDTO conversionToAttr(CmsActivityAttrValue cmsActivityAttrValue) {
        ActivityAttrValueDTO dto = new ActivityAttrValueDTO();
        BeanUtil.copyProperties(cmsActivityAttrValue, dto);
        return dto;
    }

    public Boolean isUserActivitySignIn(Long studentUserId, Long activityId) {

        Integer count = signInMapper.countToDayActivityId(studentUserId, activityId);
        log.info("count = {}", count);
        if (count > 0) {
            return true;
        }
        return false;
    }

    public Boolean isUserSignIn(Long studentUserId, Long activityId, Long calendarId) {
        log.info("studentUserId = {},  calendarId = {}", studentUserId, calendarId);
        int count = userSignInService.count(new LambdaQueryWrapper<CmsUserSignIn>()
                .eq(CmsUserSignIn::getUserId, studentUserId)
                .eq(CmsUserSignIn::getScenesId, activityId)
                .eq(CmsUserSignIn::getCalendarId, calendarId)
                .last("limit 1"));
        log.info("count = {}", count);
        if (count > 0) {
            return true;
        }
        return false;
    }

    private List<ShowCommonActivityVo> conversionToShowActivityVoList(List<CmsCommonActivity> list) {
        List<ShowCommonActivityVo> voList = list.stream().map(
                pojo -> {
                    ShowCommonActivityVo vo = conversionToShowActivityVo(pojo);
                    //  附加属性
                    vo.setValueDTOList(getAttrList(pojo.getId()));
                    return vo;
                }
        ).collect(Collectors.toList());
        return voList;
    }

    private ShowCommonActivityVo conversionToShowActivityVo(CmsCommonActivity pojo) {
        ShowCommonActivityVo vo = new ShowCommonActivityVo();
        BeanUtil.copyProperties(pojo, vo);

        Map<String, Object> map = getActivityStatus(pojo.getId());
        ActivityStatusEnum activityStatusEnum = (ActivityStatusEnum) map.get("activityStatus");

        vo.setActivityStatus(activityStatusEnum.getCode());
        if (activityStatusEnum.equals(ActivityStatusEnum.NOT_START)) {
            vo.setSignUpDate("未开始");
        } else {
            vo.setSignUpDate(map.get("startDateFormat") + " 至 " + map.get("endDateFormat"));
        }
        return vo;
    }

    private ManagerCommonActivityVo conversionToManagerActivityVo(CmsCommonActivity pojo) {
        ManagerCommonActivityVo vo = new ManagerCommonActivityVo();
        BeanUtil.copyProperties(pojo, vo);

        Map<String, Object> map = getActivityStatus(pojo.getId());
        vo.setActivityStatus(((ActivityStatusEnum) map.get("activityStatus")).getCode());
        vo.setSignUpDate(DateUtils.format(pojo.getGmtCreate(), "yy-MM-dd HH:mm") + " 至 " + map.get("endDateFormat"));
        return vo;
    }

    private List<CmsActivityManagerUser> conversionToManagerUserPojo(Long activityId, List<ManagerUserForm> managerUserList) {
        List<CmsActivityManagerUser> list = managerUserList.stream().map(manager -> {
            return CmsActivityManagerUser.builder()
                    .activityId(activityId)
                    .managerUserId(manager.getId())
                    .managerUserName(manager.getName())
                    .build();
        }).collect(Collectors.toList());
        return list;
    }

    private TodayCommonActivityVo conversionToTodayVo(CmsCommonActivity pojo) {
        TodayCommonActivityVo vo = new TodayCommonActivityVo();
        BeanUtil.copyProperties(pojo, vo);

        // 转换活动类型 后期优化
        CmsActivityType activityType = typeService.getById(pojo.getActivityTypeId());
        if (ObjectUtils.isNotEmpty(activityType)) {
            vo.setActivityTypeName(activityType.getName());
        } else {
            vo.setActivityTypeName("活动");
        }

        return vo;
    }

    public boolean userSignInForVenue(Long userId, Long activityId) {
        // 校验是否已签到
        if (isUserActivitySignIn(userId, activityId)) {
            throw new BizException("您已经签到过来，请勿重复签到");
        }

        CmsUserSignIn userSignIn = CmsUserSignIn.builder()
                .userId(userId)
                .scenesId(activityId)
                .calendarId(0L)
                .signInDate(new Date())
                .type(0)
                .build();
        log.info("userSignIn = {}", userSignIn);
//        return userSignInService.save(userSignIn);
        return false;
    }

    /**
     * 判断是否是特殊的场馆预约
     *
     * @param activity 活动ID
     * @return 是否
     */
    private boolean isVenue(CmsCommonActivity activity) {
        String value = commonConfigService.getByConfigKey(ConfigKeyConstant.ACTIVITY_VENUE_CODE_LIST).getValue();
        List<String> codeList = Arrays.asList(value.split(","));
        if (CollectionUtils.isEmpty(codeList)) {
            throw new BizException("系统异常");
        }

        List<Long> venueActivityTypeIdList = findVenueActivityTypeId();
        if (CollectionUtils.isEmpty(venueActivityTypeIdList)) {
            return false;
        }

        boolean isVenue = false;
        for (Long activityTypeId : venueActivityTypeIdList) {
            if (activityTypeId.equals(activity.getActivityTypeId())) {
                isVenue = true;
            }
        }
        return isVenue;
    }

    /**
     * 特殊的场馆预约
     */
    private List<Long> findVenueActivityTypeId() {
        String value = commonConfigService.getByConfigKey(ConfigKeyConstant.ACTIVITY_VENUE_CODE_LIST).getValue();
        List<String> codeList = Arrays.asList(value.split(","));
        if (CollectionUtils.isEmpty(codeList)) {
            throw new BizException("系统异常");
        }

        return codeList.stream().map(code -> {
            CmsActivityType activityType = typeService.getByCode(code);
            log.info("activityType = {}", activityType);
            return activityType.getId();
        }).collect(Collectors.toList());
    }


}
